import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cli/theme/theme.dart';
import 'package:flutter_cli/utils/common.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart' as GetX;
import 'dart:async';
import 'package:flutter_ume/flutter_ume.dart'; // UME 框架
import 'package:flutter_ume_kit_console/flutter_ume_kit_console.dart'; // debugPrint 插件包
import 'package:flutter_ume_kit_device/flutter_ume_kit_device.dart'; // 设备信息插件包
import 'package:flutter_ume_kit_perf/flutter_ume_kit_perf.dart'; // 性能插件包
import 'package:flutter_ume_kit_show_code/flutter_ume_kit_show_code.dart'; // 代码查看插件包
import 'package:flutter_ume_kit_ui/flutter_ume_kit_ui.dart';
import 'package:flutter_ume_kit_dio/flutter_ume_kit_dio.dart';

import 'api/api.dart';
import 'config/config.dart';
import 'route/not_found_page.dart';
import 'route/router.dart';
import 'service/app_router_service.dart';
import 'utils/log.dart'; // UI 插件包

void main() {
  /// Dart异常捕获
  runZonedGuarded(() {
    _initBeforeRunApp().then((value) {
      _realRunApp();
    });
  }, (exception, stackTrace) async {
    _customerReport(exception, stackTrace);
  });
}

void _realRunApp() {
  if (Config.showDebugTool == false) {
    Log.init(tag: "正式环境LogUtil", isDebug: false, maxLen: 800);
    runApp(const RootPage());
  } else {
    Log.init(tag: "测试环境LogUtil", isDebug: true, maxLen: 800);
    runApp(const RootPage());
    PluginManager.instance
      ..register(const WidgetInfoInspector())
      ..register(const WidgetDetailInspector())
      ..register(const ColorSucker())
      ..register(AlignRuler())
      ..register(const ColorPicker()) // 新插件
      ..register(const TouchIndicator()) // 新插件
      ..register(Performance())
      ..register(const ShowCode())
      ..register(const MemoryInfoPage())
      ..register(CpuInfoPage())
      ..register(const DeviceInfoPanel())
      ..register(Console())
      ..register(DioInspector(dio: DioUtil().dio));
    // flutter_ume 0.3.0 版本之后
    runApp(const UMEWidget(enable: true, child: RootPage())); // 初始化
  }
}

/// 自定义异常上报逻辑
void _customerReport(Object exception, StackTrace? stack) {
  Log.d("kReleaseMode:$kReleaseMode"); //false | true
  String tag = kReleaseMode == true ? "RELEASE" : "DEV" + "_CONSOLE";
  StackTrace trace = stack ?? StackTrace.fromString("empty");
  Log.d("$tag>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Exception:\n$exception");
  Log.d("$tag>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Stack:\n$trace");
}

/// 在启动之前要做的异步任务
Future<bool> _initBeforeRunApp() async {
  //runApp前调用，初始化绑定，手势、渲染、服务等
  WidgetsFlutterBinding.ensureInitialized();

  // Get 配置
  GetX.Get.config(
    defaultTransition: GetX.Transition.noTransition,
    enableLog: true,
    defaultPopGesture: true,
  );

  // sp初始化
  SpUtil.getInstance();
  // 初始化全局Global
  Get.put(GlobalController());
  // 修改主题
  Get.changeTheme(global.theme.value == ThemeStyle.light.value
      ? ThemeUtils.lightTheme()
      : ThemeUtils.darkTheme());
  // EasyLoading初始化
  EasyLoading.init();
  // 设置Android状态栏
  Utils.setSystemUi();
  // 打开视觉调试开关
  //debugPaintSizeEnabled = true;
  return true;
}

class RootPage extends StatelessWidget {
  const RootPage({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return OKToast(
      textPadding:
          const EdgeInsets.only(left: 20, right: 20, top: 10, bottom: 10),
      radius: 12,
      child: ScreenUtilInit(
          designSize: const Size(750, 1334),
          minTextAdapt: true,
          splitScreenMode: true,
          builder: (context, child) {
            return GetX.GetMaterialApp(
              title: "flutter_cli",
              debugShowCheckedModeBanner: false,
              defaultTransition: GetX.Get.defaultTransition,
              opaqueRoute: GetX.Get.isOpaqueRouteDefault,
              popGesture: GetX.Get.isPopGestureEnable,
              transitionDuration: GetX.Get.defaultTransitionDuration,
              // 是否打开性能测试层
              showPerformanceOverlay: false,
              theme: ThemeUtils.lightTheme(),
              darkTheme: ThemeUtils.darkTheme(),
              themeMode: ThemeMode.light,
              getPages: AppPages.pages,
              initialRoute: AppPages.launch,
              builder: EasyLoading.init(builder: (context, Widget? child) {
                return MediaQuery(
                  ///设置文字大小不随系统设置改变
                  data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
                  child: child ?? const SizedBox(),
                );
              }),
              // 监听路由打印
              navigatorObservers: [GetX.GetObserver(), AppRouterObserver()],
              // 设置未知路由的处理
              // unknownRoute: GetPage(name: '/not-found', page: () => NotFoundPage()),
              onUnknownRoute: (settings) {
                String name = settings?.name ?? "";
                Log.e("未匹配到路由:$name");
                return GetX.GetPageRoute(
                  page: () => const NotFoundPage(),
                );
              },
            );
          }),
    );
  }
}
